﻿using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading;
using YAWD.Properties;
using YAWD.Utils;

namespace YAWD.BL.Providers
{
    class GoodFon : IProvider
    {
        public string URL { get; set; }
        public string Path { get; set; }
        public string FirstImage { get; set; }
        public string LastDwImage { get; set; }
        public DateTime LastUpdated { get; set; }
        public string LastId { get; set; }

        private bool _isCancelationPending;
        private double _current;
        private string _currentImage = string.Empty;
        private IList<string> _images;

        public double Current
        {
            get { return this._current; }
            set
            {
                this._current = value;
                OnProgressChanged(EventArgs.Empty);
            }
        }
        public string CurrentImage
        {
            get { return this._currentImage; }
            set
            {
                this._currentImage = value;
                OnCurrentImageChanged(EventArgs.Empty);
            }
        }
        public IList<string> Images
        {
            get { return this._images; }
            set
            {
                this._images = value;
                OnImagesChanged(EventArgs.Empty);
            }
        }

        public event EventHandler ProgressChanged;
        public event EventHandler CurrentImageChanged;
        public event EventHandler ImagesChanged;

        public IProvider Init()
        {
            return Util.ReadProviderSettings(this);
        }
        protected virtual void OnProgressChanged(EventArgs e)
        {
            if (this.ProgressChanged != null)
                this.ProgressChanged(this, e);
        }
        protected virtual void OnCurrentImageChanged(EventArgs e)
        {
            if (this.CurrentImageChanged != null)
                this.CurrentImageChanged(this, e);
        }
        protected virtual void OnImagesChanged(EventArgs e)
        {
            if (this.ImagesChanged != null)
                this.ImagesChanged(this, e);
        }

        public int getAll()
        {
            return 0;
        }
        private int getImages(int start)
        {
            this._isCancelationPending = false;

            int downloadedImage = 0;
            int end = getLatest();

            int nbrItems = end - start;
            double interleave = (double)100 / nbrItems;
            IList<SyndicationItem> items = rssReader.getAll(new Uri(URL));

            Settings settings = Settings.Default;
            string initPath;
            if (string.IsNullOrWhiteSpace(settings.WallPapersPath))
                initPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            else
                initPath = settings.WallPapersPath;

            int lastIndex;

            if (int.TryParse(this.CurrentImage, out lastIndex) == false)
                lastIndex = 0;

            for (int i = end-1; i >= start; i--)
            {
                //exit if the user cancels
                if (this._isCancelationPending == true)
                {
                    Util.SaveToConfigFile("LastUpdated", DateTime.Now.ToShortDateString(), this);
                    return downloadedImage;
                }

                Current += interleave;

                string url = items[i].Links[0].Uri.ToString();
                string webPage = Util.GetHtmlPage(url, Encoding.UTF8);
                Thread.Sleep(5000);
                if (webPage != null)
                {
                    string strParsing = @"Скачать оригинал";
                    int intTemp = webPage.IndexOf(strParsing, StringComparison.Ordinal);
                    if (intTemp > -1)
                    {
                        webPage = webPage.Substring(intTemp + strParsing.Length);
                        strParsing = @"href=""";
                        webPage = webPage.Substring(webPage.IndexOf(strParsing, StringComparison.Ordinal) + strParsing.Length);
                        strParsing = @"""";
                        url = @"http://www.goodfon.ru" + webPage.Substring(0, webPage.IndexOf(strParsing, StringComparison.Ordinal)).Trim();
                        webPage = Util.GetHtmlPage(url, Encoding.UTF8,url);
                        Thread.Sleep(3000);
                        if (webPage != null)
                        {
                            strParsing = @"</noindex>";
                            intTemp = webPage.IndexOf(strParsing, StringComparison.Ordinal);
                            webPage = webPage.Substring(intTemp + strParsing.Length);
                            strParsing = @"href=""";
                            webPage = webPage.Substring(webPage.IndexOf(strParsing, StringComparison.Ordinal) + strParsing.Length);
                            strParsing = @"""";
                            string filepath = webPage.Substring(0, webPage.IndexOf(strParsing, StringComparison.Ordinal)).Trim();
                            string index = filepath.Substring(filepath.LastIndexOf(@"/") + @"/".Length);
                            if (File.Exists(System.IO.Path.Combine(initPath, Utils.Providers.GoodFon.ToString(),index))==false)
                            try
                            {
                                if (Util.GetImage(filepath, string.Empty,this.GetType().Name, index, true) > 0)
                                {
                                    downloadedImage++;
                                    this.LastDwImage = index;
                                    Util.SaveToConfigFile("LastDwImage", this.LastDwImage, this);
                                    CurrentImage = this.LastDwImage;
                                    Images = Util.LoadImage(Utils.Providers.GoodFon, initPath);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            this.LastUpdated = DateTime.Now;
            Util.SaveToConfigFile("LastUpdated", DateTime.Now.ToShortDateString(), this);
            return downloadedImage;
        }
        public int update()
        {
            return getImages(0);
        }
        public void CancelAsync()
        {
            this._isCancelationPending = true;
        }

        private int getLatest()
        {
            return rssReader.getAll(new Uri(URL)).Count;
        }

    }
}

